package com.atguigu.tingshu.user.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;

@Configuration
public class LoginPrivateKeyConfig {
    @Resource
    InitConfig initConfig;

    /**
     * 加载私钥到容器
     * @return
     */

    @Bean
    public RSAPrivateKey guiguPrivateKey() {
        //加载classpath秘钥文件
        ClassPathResource resource = new ClassPathResource(initConfig.getLocation());
        //密钥工厂对象，加载密钥文件，并且通过密码打开文件
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(resource, initConfig.getSecret().toCharArray());
        //获取秘钥通过别名+密钥的访问密码获取
        KeyPair keyPair = keyFactory.getKeyPair(initConfig.getAlias(), initConfig.getPassword().toCharArray());
        //获取私钥注入容器
        return (RSAPrivateKey)keyPair.getPrivate();
    }
}

